<template>
    <div v-loading.fullscreen.lock="taskNum>0" 
    element-loading-text="批量识别中,请稍等..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)">
       <el-card shadow="never" class="box-card search_head" style="margin-bottom: 15px;">
           <el-form :model="query" inline style="max-width: calc(100% - 200px );">
               <el-form-item label="发票号码:">
                 <el-input size="small" v-model="query.发票号码"></el-input>
               </el-form-item>
               <el-form-item label="发票类型:">
                 <el-input size="small" v-model="query.发票类型"></el-input>
               </el-form-item>
               <el-form-item label="销售方名称:">
                 <el-input size="small" v-model="query.销售方名称"></el-input>
               </el-form-item>
               <el-form-item label="购买方名称:">
                 <el-input size="small" v-model="query.购买方名称"></el-input>
               </el-form-item>
               <el-form-item label="开票日期:">
                 <el-date-picker
                   v-model="daterange"
                   type="daterange"
                   value-format="timestamp"
                   clearable
                   :unlink-panels="true"
                   range-separator="至"
                   start-placeholder="开始日期"
                   end-placeholder="结束日期">
                 </el-date-picker>
               </el-form-item>
               
               <el-form-item label="" >
                 <el-button
                   @click="queryClick" 
                   size="mini"
                   type="primary"
                 >
                   查询
                 </el-button>
                 <el-button
                   @click="resetGet"
                   size="mini"
                   type="success"
                 >
                   重置
                 </el-button>
               </el-form-item>
           </el-form>
           <div style="position: absolute;right: 20px;top: 20px;">
               <el-upload
                 style="display: inline-block;"
                 accept=".jpeg,.jpg,.png,.pdf"
                 action=""
                 :show-file-list="false"
                 :http-request="httpUpload"
               >
                 <el-button
                   size="mini"
                   type="primary"
                 >
                   发票识别
                 </el-button>
               </el-upload>
               <el-upload
                 style="display: inline-block;margin-left: 10px;"
                 accept=".jpg,.png,.pdf"
                 action=""
                 multiple
                 :limit="10"
                 :auto-upload="true"
                 :show-file-list="false"
                 :http-request="multipleUpload"
               >
                 <el-button
                   size="mini"
                   type="warning"
                 >
                   批量识别
                 </el-button>
               </el-upload>
           </div>
           
        </el-card>
        <div class="container">
            <div style="position: relative;min-height: 35px;">
                <el-button
                  style="float: right;"   
                  size="mini"
                  type="success"
                  @click="getExportData"
                >
                  导出Excel
                </el-button>
                <el-form  inline style="max-width: calc(100% - 100px );">
                    <el-form-item label="筛选条数:">
                      0000
                    </el-form-item>
                    <el-form-item label="合计金额:">
                      0000
                    </el-form-item>
                    <el-form-item label="合计税额:">
                      0000
                    </el-form-item>
                    <el-form-item label="价税合计:">
                      0000
                    </el-form-item>
                </el-form>    
                
            </div>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="发票号码" label="发票号码">
                </el-table-column>
                <el-table-column prop="发票代码" label="发票代码">
                </el-table-column>
                <el-table-column prop="开票日期" label="开票日期">
                </el-table-column>
                <el-table-column prop="校验码" label="校验码">
                </el-table-column>
                <el-table-column prop="销售方识别号" label="销售方识别号">
                </el-table-column>
                <el-table-column prop="销售方名称" label="销售方名称">
                </el-table-column>
                <el-table-column prop="购买方识别号" label="购买方识别号">
                </el-table-column>
                <el-table-column prop="购买方名称" label="购买方名称">
                </el-table-column>
                <el-table-column prop="开票内容" label="开票内容" width="220">
                </el-table-column>
                <el-table-column prop="合计金额" label="合计金额(¥)" width="100">
                </el-table-column>
                <el-table-column prop="合计税额" label="合计税额(¥)" width="100">
                </el-table-column>
                <el-table-column prop="价税合计" label="价税合计(¥)" width="100">
                </el-table-column>
                <el-table-column prop="价税合计(大写)" label="价税合计(大写)">
                </el-table-column>
                <el-table-column prop="发票类型" label="发票类型">
                </el-table-column>
                <el-table-column prop="发票消费类型" label="发票消费类型">
                </el-table-column>
                <el-table-column prop="省" label="省份">
                </el-table-column>
                <el-table-column prop="备注" label="备注">
                </el-table-column>
                <el-table-column prop="其他备注" label="其他备注">
                </el-table-column>
                <el-table-column prop="file" label="识别发票">
                    <template slot-scope="scope">
                        <a target="_blank" title="点击查看" :href="scope.row.file">{{scope.row.fileName}}</a>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                    <template slot-scope="scope">
                        <el-button @click="toDel(scope.row)" style="color: #F56C6C;" type="text" size="small">删除</el-button>
                        <el-button @click="toUpdate(scope.row)" type="text" size="small">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="margin-top: 5px;" @size-change="getData" @current-change="getData" :current-page.sync="pages.page"
                :page-sizes="[10, 20, 100]" :page-size.sync="pages.size"
                layout="total, sizes, prev, pager, next, jumper" :total="pages.total">
            </el-pagination>
        </div>
        <el-dialog title="发票信息" center width="1200px" :visible.sync="dialogFormVisible">
          <el-form :model="form" label-width="150px">
              <el-row>
                  <el-col :span="12">
                      <el-form-item label="发票号码" required>
                        <el-input size="small" class="w300" v-model="form.发票号码"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="发票代码" >
                        <el-input size="small" class="w300" v-model="form.发票代码"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="开票日期" >
                        <el-input size="small" class="w300" v-model="form.开票日期"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="校验码" >
                        <el-input size="small" class="w300" v-model="form.校验码"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="24">
                      <el-form-item label="开票内容" >
                          <el-input
                            size="small"
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="form.开票内容">
                          </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="销售方识别号" >
                        <el-input size="small" class="w300" v-model="form.销售方识别号"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="销售方名称" >
                        <el-input size="small" class="w300" v-model="form.销售方名称"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="购买方识别号" >
                        <el-input size="small" class="w300" v-model="form.购买方识别号"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="购买方名称" >
                        <el-input size="small" class="w300" v-model="form.购买方名称"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="合计金额(¥)" >
                        <el-input size="small" class="w300" v-model="form.合计金额"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="合计税额(¥)" >
                        <el-input size="small" class="w300" v-model="form.合计税额"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="价税合计(¥)" >
                        <el-input size="small" class="w300" v-model="form.价税合计"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="价税合计(大写)" >
                        <el-input size="small"  class="w300" v-model="form['价税合计(大写)']"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="发票类型" >
                        <el-input size="small"  class="w300" v-model="form.发票类型"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                      <el-form-item label="发票消费类型" >
                        <el-input size="small"  class="w300" v-model="form.发票消费类型"></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="省份" >
                       <el-input size="small"  class="w300" v-model="form.省"></el-input>
                     </el-form-item>
                    </el-col>
                  <el-col :span="12">
                      <el-form-item label="发票备注" >
                        <el-input size="small" v-model="form.备注"></el-input>
                      </el-form-item>
                     </el-col>
                  <el-col :span="24">
                      <el-form-item label="其他备注" >
                          <el-input
                            size="small"
                            type="textarea"
                            :rows="2"
                            placeholder="此处为公司自己的备注"
                            v-model="form.其他备注">
                          </el-input>
                      </el-form-item>
                     </el-col>
                   <el-col :span="24">
                       <el-form-item label="识别发票" >
                           <a target="_blank" title="点击查看" :href="form.file">{{form.fileName}}</a>
                       </el-form-item>
                    </el-col>  
              </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button @click="save" type="primary" >保 存</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
    import ajax from '@/ajax';
    // var XLSX = require('xlsx'); 
    import XLSX from 'xlsx-js-style'
    export default {
        name: 'bill',
        data() {
            return {
                taskNum:0,
                daterange:null,
                methodType:"post",
                query:{
                    发票号码:null,
                    发票类型:null,
                    销售方名称:null,
                    购买方名称:null,
                    开票日期1:null,
                    开票日期2:null,
                },
                form:{
                    _id:"",
                    发票代码:"",
                    发票号码:"",
                    开票日期:"",
                    校验码:"",
                    销售方识别号:"",
                    销售方名称:"",
                    购买方识别号:"",
                    购买方名称:"",
                    开票内容:"",
                    合计金额:"",
                    合计税额:"",
                    价税合计:"",
                    "价税合计(大写)":"",
                    发票类型:"",
                    发票消费类型:"",
                    省:"",
                    备注:"",
                    其他备注:"",
                    
                },
                defaultForm:null,
                pages: {
                    page: 1,
                    size: 10,
                    total: 0
                },
                dialogFormVisible:false,
                tableData: []
            }
        },
        created() {
           this.defaultForm = JSON.parse(JSON.stringify(this.form)) 
           this.getData()
          // console.log(this.matchNum(0)); //['1234']
        },
        methods: {
            getExportData(){
                if(this.daterange && this.daterange.length){
                    this.query.开票日期1 = this.daterange[0] - 1
                    this.query.开票日期2 = this.daterange[1] + 24*60*60*1000
                }else{
                    this.query.开票日期1 = null
                    this.query.开票日期2 = null
                }
                let skip = (this.pages.page - 1)*this.pages.size
                let limit = this.pages.size
                ajax('bill',{
                    query:this.query
                },'export').then(res=>{
                    this.exportExcel(res.content)
                })
            },
            exportExcel(tableData){
                if(tableData.length ===0){
                    this.$message.error("无可导出的数据！")
                    return
                }
                this.$prompt('请填写导出表格的名称', '提示', {
                          confirmButtonText: '确定',
                          cancelButtonText: '取消',
                          inputValue:"发票统计"
                        }).then(( { value } ) => {
                          let headers =  JSON.parse(JSON.stringify(this.defaultForm))
                          delete headers._id
                          delete headers.其他备注
                          delete headers.省
                          let data = []
                          tableData.forEach(i=>{
                              let item = {}
                              for(let a in headers){
                                  item[a] = i[a]
                              }
                              item.省份 = i.省
                              data.push(item)
                          })
                          var worksheet = XLSX.utils.json_to_sheet(data);  
                          worksheet['!cols'] = [  
                            { wch: 10 },   
                            { wch: 10 },   
                            { wch: 10 }, 
                            { wch: 10 }, 
                            { wch: 20 }, 
                            { wch: 20 }, 
                            { wch: 20 }, 
                            { wch: 20 }, 
                            { wch: 40 }, 
                            { wch: 10 }, 
                            { wch: 10 }, 
                            { wch: 10 }, 
                            { wch: 20 }, 
                            { wch: 10 }, 
                            { wch: 20 }, 
                            { wch: 10 }, 
                            { wch: 10 }, 
                          ];  
                          let headStyle = {
                              font: {
                                name:"宋体",
                                bold: true,
                                sz: 12,
                              },
                              border:{
                                  left:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  right:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  top:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  bottom:{
                                      style:"thin",
                                      color:"000000"
                                  },
                              },  
                              fill: {  
                                fgColor: {  
                                  rgb: 'F5F5F5'   
                                }  
                              },
                              alignment: { wrapText: true,horizontal:'center'}
                          }
                          let bodyStyle = {
                              font: {
                                name:"宋体",
                                sz: 11,//设置标题的字号
                              }, 
                              border:{
                                  left:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  right:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  top:{
                                      style:"thin",
                                      color:"000000"
                                  },
                                  bottom:{
                                      style:"thin",
                                      color:"000000"
                                  },
                              },  
                              alignment: { wrapText: true,vertical: 'center'} 
                          }
                          for (let key in worksheet) {
                              if(key != '!cols' && key != '!ref'){
                                  if(this.matchNum(key) == 1){
                                      worksheet[key].s = headStyle
                                  }else{
                                      worksheet[key].s = bodyStyle
                                  }
                              }
                          }
                          var workbook = XLSX.utils.book_new();  
                          XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");  
                          XLSX.writeFile(workbook, (value || '发票统计') + '.xlsx');
                        }).catch(() => {
                               
                        });
            },
            resetGet(){
                this.pages.page = 1
                this.query.发票号码 = null
                this.query.发票类型 = null
                this.query.销售方名称 = null
                this.query.购买方名称 = null
                this.query.开票日期1 = null
                this.query.开票日期2 = null
                this.daterange = null
                this.getData()
            },
            queryClick(){
                this.pages.page = 1
                this.getData()
            },
            getData() {
                if(this.daterange && this.daterange.length){
                    this.query.开票日期1 = this.daterange[0] - 1
                    this.query.开票日期2 = this.daterange[1] + 24*60*60*1000
                }else{
                    this.query.开票日期1 = null
                    this.query.开票日期2 = null
                }
                let skip = (this.pages.page - 1)*this.pages.size
                let limit = this.pages.size
                ajax('bill',{
                    skip,
                    limit,
                    query:this.query
                },'get').then(res=>{
                    // console.log(res)
                    this.tableData = res.content
                    this.pages.total = res.count
                })
            },
            toUpdate(row){
                this.form =  JSON.parse(JSON.stringify(row))
                this.methodType = "put"
                this.dialogFormVisible = true
            },
            toDel(row){
                this.$confirm('确定删除该条数据？', '提示', {
                          confirmButtonText: '确定',
                          cancelButtonText: '取消',
                          type: 'warning'
                }).then(() => {
                    ajax('bill',{
                        _id:row._id
                    },"delete").then(res=>{
                        this.$message.success("删除成功")
                        this.getData()
                    })
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消删除'
                  });          
                });
            },
            save(){
                ajax('bill',this.form,this.methodType).then(res=>{
                    console.log(res)
                    this.$message.success("保存成功")
                    this.dialogFormVisible = false
                    if(this.methodType==='post'){
                        this.pages.page = 1
                    }
                    this.getData()
                })
            },
            
            // xxcCloud.getTempFileURL({
            //     fileList:[{
            //         fileID:res.fileID
            //     }]
            // }).then(res1=>{
            //     console.log(res1)
            // })
            multipleUpload(file){
                this.taskNum++
                this.uploadAndOcr(file.file).then(dataJson=>{
                    ajax('bill',dataJson,"post").then(res=>{
                        this.taskNum--
                        if(this.taskNum==0){
                            this.$message.success("批量识别成功")
                            if(this.methodType==='post'){
                                this.pages.page = 1
                            }
                            this.getData()
                        }
                    })
                })
            },
            httpUpload(file){
                 const loading = this.$loading({
                          lock: true,
                          text: '发票上传识别中，请稍等...',
                          spinner: 'el-icon-loading',
                          background: 'rgba(0, 0, 0, 0.7)'
                        });
                this.uploadAndOcr(file.file).then(dataJson=>{
                    this.form = dataJson
                    this.methodType = "post"
                    this.dialogFormVisible = true
                    loading.close()
                })
            },
            uploadAndOcr(file){
                return new Promise((resolve)=>{
                    const currentFile = file
                    let random = new Date().getTime()
                    let fileName = currentFile.name
                    var data = {
                        cloudPath:'ccm_bill/' + random + fileName,
                        file: currentFile
                    }
                    xxcCloud.uploadFile(data).then(res=>{
                        if(res.fileID){
                            let url = "https://6363-ccg-database-1gns3p717137a34c-1322979516.tcb.qcloud.la/ccm_bill/" + random + fileName
                            ajax('ocr',url).then(res2=>{
                                console.log(res2)
                                let VatInvoiceInfo = {}
                                res2.VatInvoiceInfos.forEach(i=>{
                                    VatInvoiceInfo[i.Name] = i.Value
                                })
                                let dataJson = {}
                                for(let k in this.defaultForm){
                                    if(['合计金额','合计税额'].indexOf(k)>-1){
                                        dataJson[k] = +this.matchNum(VatInvoiceInfo[k])
                                    }else{
                                        dataJson[k] = VatInvoiceInfo[k]===0?0:(VatInvoiceInfo[k] || "")
                                    }
                                }
                                let items = res2.Items.map(function(i){
                                    return i.Name
                                })
                                dataJson._id = res2.RequestId
                                //兼容处理  购买方识别号 销售方识别号 价税合计
                                dataJson['价税合计'] = +this.matchNum(VatInvoiceInfo['小写金额'] || VatInvoiceInfo['价税合计(小写)'])
                                dataJson['购买方识别号'] = VatInvoiceInfo['购买方识别号'] || VatInvoiceInfo['购买方统一社会信用代码/纳税人识别号']
                                dataJson['销售方识别号'] = VatInvoiceInfo['销售方识别号'] || VatInvoiceInfo['销售方统一社会信用代码/纳税人识别号']
                                dataJson['开票时间戳'] = ""
                                if(VatInvoiceInfo['开票日期']){
                                    dataJson['开票时间戳'] =  new Date(VatInvoiceInfo['开票日期'].replace("年","-").replace("月","-").replace("日","")).getTime()
                                }
                                dataJson.file = url
                                dataJson.fileName = fileName
                                dataJson['开票内容'] = items.join("； ")
                                console.log(dataJson)
                                resolve(dataJson)
                            })
                        }
                    })
                })

            }
            
        }
    }
</script>

<style scoped>
</style>
